package com.yucc.girlimage.ui;

import java.io.BufferedOutputStream;
import java.io.ByteArrayOutputStream;
import java.lang.ref.WeakReference;
import java.util.HashMap;

import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Bundle;
import android.os.Handler;
import android.os.HandlerThread;
import android.os.Looper;
import android.os.Message;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.ImageView;

import com.actionbarsherlock.R.style;
import com.actionbarsherlock.app.SherlockActivity;
import com.actionbarsherlock.view.Menu;
import com.actionbarsherlock.view.MenuItem;
import com.umeng.analytics.MobclickAgent;
import com.umeng.api.sns.UMSNSException;
import com.umeng.api.sns.UMSnsService;
import com.umeng.api.sns.UMSnsService.DataSendCallbackListener;
import com.umeng.api.sns.UMSnsService.RETURN_STATUS;
import com.umeng.fb.NotificationType;
import com.umeng.fb.UMFeedbackService;
import com.umeng.update.UmengUpdateAgent;
import com.waps.AppConnect;
import com.yucc.girlimage.Config;
import com.yucc.girlimage.GirlsApplication;
import com.yucc.girlimage.R;
import com.yucc.girlimage.util.ImageFetcher;
import com.yucc.girlimage.util.Utils;

public class MainMenuActivity extends SherlockActivity implements OnClickListener {
	private ImageView mImageAd ;
	private Button mBtnMyGirls ;
	private Button mBtnGirlsStreet ;
	private Button mBtnSpecial ;
	private ImageView mImageSpecial ;
	private Button mBtnApps ;
	private AutoPlayAd mPlayer ;
	private int [] mDrawableIds ;
	private int mPosition = 0;
	byte [] mBytesForShare ;
	
	private Exit mExit ;
	
    @Override
    public void onCreate(Bundle savedInstanceState) {
    	setTheme(style.Theme_Sherlock_Light_DarkActionBar) ;
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_mainmenu);
        
        MobclickAgent.onError(this);
        
        MobclickAgent.updateOnlineConfig(this);
        
        mDrawableIds = new int[]{R.drawable.a2020120,R.drawable.sexy,R.drawable.blackyarm,R.drawable.autodyne} ;
        mPlayer = new AutoPlayAd(new AdMainHandler(this)) ;
        
        AppConnect.getInstance(Config.WAPS_ID,Config.WAPS_PID,this); 
        
        mExit = new Exit() ;
        
        setupView() ;
        setupListener() ;
        
        UmengUpdateAgent.setUpdateOnlyWifi(false) ;
	    UmengUpdateAgent.update(getParent());
    }
    
    @Override
    protected void onResume() {
    	// TODO Auto-generated method stub
    	super.onResume();
    	mPlayer.startPlay() ;
    }
    
    @Override
    protected void onPause() {
    	// TODO Auto-generated method stub
    	super.onPause();
    	mPlayer.stopPlay() ;
    	ImageFetcher.getHttpDiskLruCache(this).clearCache() ;
    }
    
	@Override
	protected void onDestroy() {
		// TODO Auto-generated method stub
		super.onDestroy();
		//停止线程
		mPlayer.stop() ;
		AppConnect.getInstance(this).finalize();
	}
	
	@Override
    public boolean onCreateOptionsMenu(Menu menu) {
        //Used to put dark icons on light action bar

        menu.add("分享").setIcon(android.R.drawable.ic_menu_share)
            .setShowAsAction(MenuItem.SHOW_AS_ACTION_ALWAYS);
        menu.add("反馈").setIcon(android.R.drawable.ic_menu_edit)
        .setShowAsAction(MenuItem.SHOW_AS_ACTION_IF_ROOM);

        return true;
    }
	
	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
		if("分享".equals(item.getTitle())){
			shareImage() ;
			return true ;
		} else if("反馈".equals(item.getTitle())){
			UMFeedbackService.enableNewReplyNotification(
					this, NotificationType.AlertDialog);
			UMFeedbackService.setGoBackButtonVisible();

			UMFeedbackService.openUmengFeedbackSDK(this);
		}
		return super.onOptionsItemSelected(item);
	}
	
    private void setupView(){
    	mImageAd = (ImageView) findViewById(R.id.image_ad) ;
    	mImageSpecial = (ImageView) findViewById(R.id.img_special) ;
    	mBtnMyGirls = (Button) findViewById(R.id.btn_fav) ;
    	mBtnGirlsStreet = (Button) findViewById(R.id.btn_girl_store) ;
    	mBtnSpecial = (Button) findViewById(R.id.btn_special) ;
    	mBtnApps = (Button) findViewById(R.id.btn_hot_app) ;
    }
    
    private void setupListener(){
    	mImageAd.setOnClickListener(this) ;
    	mImageSpecial.setOnClickListener(this) ;
    	mBtnMyGirls.setOnClickListener(this) ;
    	mBtnGirlsStreet.setOnClickListener(this) ;
    	mBtnSpecial.setOnClickListener(this) ;
    	mBtnApps.setOnClickListener(this) ;
    }
    
    protected void playNextAd(){
    	mPosition++ ;
    	if(0 > mPosition || mPosition > mDrawableIds.length -1){
    		mPosition = (mPosition + 1 ) % mDrawableIds.length ;
    	}
    	mImageAd.setImageResource(mDrawableIds[mPosition]) ;
    }
    
 // SNS分享图片，使用异步初始化加载
 	private void shareImage() {
 		DataSendCallbackListener listener = new DataSendCallbackListener(){
             @Override
             public void onDataSendFailedWithException(
                     UMSNSException exception, UMSnsService.SHARE_TO userPlatform) {
            	 exception.printStackTrace() ;
             }
             @Override
             public void onDataSendFinished(RETURN_STATUS returnStatus, UMSnsService.SHARE_TO userPlatform) {
                 switch (returnStatus)
                 {
                 case UPDATED:
                 	((GirlsApplication)getApplication()).showToast("感谢您的分享.") ;
                     break;
                 case REPEATED:
                 	((GirlsApplication)getApplication()).showToast("重复的内容分享.") ;
                     break;
                 default:
                     break;
                 }
             }
         };
 		UMSnsService.share(this, mBytesForShare, new HashMap<String, String>(), listener);
 	}
    
  //提前做好分享的数据准备
  	protected void prepreForShare() {
		Bitmap bmp = BitmapFactory.decodeResource(getResources(),R.drawable.blackyarm);
  		
  		ByteArrayOutputStream stream = new ByteArrayOutputStream();
  		BufferedOutputStream bos = new BufferedOutputStream(stream,
  				Utils.IO_BUFFER_SIZE);
  		bmp.compress(Bitmap.CompressFormat.JPEG, 90, bos);
  		mBytesForShare = stream.toByteArray();
  	}
  	
  	@Override
	public void onBackPressed() {
		if(mExit.isExit()) {
			finish() ;
			return ;
		}
		
		((GirlsApplication)getApplication()).showToast("再按一次退出程序") ;
		mExit.doExitInSeconds(3) ;
	}

	class Exit {
		private boolean isExit;
		private Runnable task;

		Exit() {
			this.task = new Runnable() {

				@Override
				public void run() {
					// TODO Auto-generated method stub
					setExit(false);
				}
			};
		}

		public void doExitInSeconds(int seconds) {
			this.isExit = true;
			HandlerThread localHandlerThread = new HandlerThread("doTask");
			localHandlerThread.start();
			Looper localLooper = localHandlerThread.getLooper();
			Handler localHandler = new Handler(localLooper);
			Runnable localRunnable = this.task;
			localHandler.postDelayed(localRunnable, seconds * 1000L);
		}

		public boolean isExit() {
			return this.isExit;
		}

		public void setExit(boolean paramBoolean) {
			this.isExit = paramBoolean;
		}
	}
    
	// 自动播放的辅助类
 	class AutoPlayAd extends Thread {
 		private AdMainHandler mMainHandler;
 		private boolean mIsAutoPlay;

 		public AutoPlayAd(AdMainHandler handler) {
 			super();
 			this.mMainHandler = handler;
 		}

 		public void startPlay(){
 			mIsAutoPlay = true ;
 			if(!isAlive()) start() ;
 		}
 		
 		public void stopPlay(){
 			mIsAutoPlay = false ;
 		}

 		@Override
 		public void run() {
 			while (true) {
 				try {
					if(mIsAutoPlay) mMainHandler.sendEmptyMessage(0);
					MainMenuActivity activity = mMainHandler.mActivity.get() ;
					if(activity  != null && activity.mBytesForShare == null){
						activity.prepreForShare() ;						
						Thread.sleep(2000);
					}else{
						Thread.sleep(3000);
					}
 				} catch (InterruptedException e) {
 					e.printStackTrace() ;
 				}
 			}
 		}
 	}
 	
 	static class AdMainHandler extends Handler {
 		
 		WeakReference<MainMenuActivity> mActivity ;

		public AdMainHandler(MainMenuActivity activity) {
			super();
			mActivity = new WeakReference<MainMenuActivity>(activity) ;
		}
		
		@Override
		public void handleMessage(Message msg) {
			MainMenuActivity theActivity = mActivity.get() ;
			if(theActivity == null) return ;
			switch (msg.what) {
			case 0:
				theActivity.playNextAd() ;
				break;

			default:
				break;
			}
		}
 	}

	@Override
	public void onClick(View v) {
		Intent intent = new Intent() ;
		String type = "" ;
		switch (v.getId()) {
			case R.id.image_ad:
			case R.id.btn_girl_store :
				type = "store" ;
				intent.setClass(this, ImageCategoryActivity.class) ;
				startActivity(intent) ;
				break;
			case R.id.btn_fav:
				type = "fav" ;
				intent.setClass(this, ImageGridDetailActivity.class) ;
				intent.putExtra(ImageGridDetailActivity.EXTRA_TITLE, getResources().getString(R.string.title_activity_fav)) ;
				startActivity(intent) ;
				break ;
			case R.id.btn_hot_app:
				type = "app" ;
				AppConnect.getInstance(this).showOffers(this);
				break ;
			case R.id.img_special:
			case R.id.btn_special:
				type = "special" ;
				intent.setClass(this, ImageGridDetailActivity.class) ;
				intent.putExtra(ImageGridDetailFragment.EXTRA_CATEGORY, "special") ;
				intent.putExtra(ImageGridDetailFragment.EXTRA_SHOW_TOAST, true) ;
				intent.putExtra(ImageGridDetailActivity.EXTRA_TITLE, getResources().getString(R.string.title_activity_special)) ;
				startActivity(intent) ;
				break ;
		}
		MobclickAgent.onEvent(this,"click_type",type);
	}
	
}